package cn.itsuorce.service.impl;

import cn.itsuorce.domain.Department;
import cn.itsuorce.mapper.BaseMapper;
import cn.itsuorce.query.BaseQuery;
import cn.itsuorce.query.DepartmentQuery;
import cn.itsuorce.service.IBaseService;
import cn.itsuorce.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.List;


@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class BaseServiceImpl<T, Q extends BaseQuery> implements IBaseService<T, Q>{

    @Autowired
    private BaseMapper<T,Q> baseMapper;

    /**
     * 新增或修改
     * @param t
     */
    @Override
    public void save(T t) {
        try {
            Class<?> clz = t.getClass();
            Field idField = clz.getDeclaredField("id");     //获取id字段  上次是获取的getId方法
            idField.setAccessible(true);    //允许访问私有的成员变量
            Object idValue = idField.get(t);//获取id字段的值
            if(idValue == null){
                baseMapper.save(t);
            }else{
                baseMapper.update(t);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(Long id) {
        baseMapper.delete(id);
    }

    @Override
    public List findAll(Q q) {
        return baseMapper.findAll(q);
    }

    @Override
    public T findOne(Long id) {
        return (T) baseMapper.findOne(id);
    }

    @Override
    public Long findTotal(Q q) {
        return baseMapper.findTotal(q);
    }

    @Override
    public Page<T> findPage(Q q) {

        //先查询总行数
        Long total = baseMapper.findTotal(q);
        List<T> rows = baseMapper.findPage(q);
        return new Page<>(total,rows);
    }

    @Override
    public void batchRemove(List ids) {
        baseMapper.batchRemove(ids);
    }
}
